import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

/// 动态实现listview
/// 1.for循环实现

void main() {
  runApp(const MaterialApp(
    title: '动态列表',
    home: ListBuilder(),
  ));
}

class Myapp extends StatefulWidget {
  const Myapp({super.key});

  @override
  State<Myapp> createState() => _MyappState();
}

class _MyappState extends State<Myapp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('动态列表'),
      ),
      body: Scaffold(
        body: ListView(
          children: _initList(),
        ),
      ),
    );
  }

  List<Widget> _initList() {
    List<Widget> list = [];
    for (var i = 0; i < 20; i++) {
      list.add(ListTile(
        title: Text('这是第 $i 行标题'),
      ));
    }

    return list;
  }
}

/// 2.listView.builder实现
///   Creates a scrollable, linear array of widgets that are created on demand.

class ListBuilder extends StatefulWidget {
  const ListBuilder({super.key});

  @override
  State<ListBuilder> createState() => _ListBuilderState();
}

class _ListBuilderState extends State<ListBuilder> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('listview.builder测试'),
      ),
      body: ListView.builder(itemBuilder: (context, index) {
        return _initData()[index];
      }),
    );
  }

  List<Widget> _initData() {
    List<Widget> list = [];
    for (var i = 0; i < 20; i++) {
      list.add(ListTile(
        title: Text('这是第  $i  行数据'),
      ));
    }
    return list;
  }
}
